package com.limit.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by IntelliJ IDEA.
 * User: liqiu
 * Date: 12-9-11
 * Time: 下午4:36
 * To change this template use File | Settings | File Templates.
 */
public class JsonUtil {
   public static JSONObject getJsonObjByUrl(String url){
      return getJsonObjByUrl(url,"utf-8");
   } 
   public static JSONObject getJsonObjByUrl(String url,String instr_charsetname){
       try {
           HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
           BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),instr_charsetname));
           String ret = "";
           String temp;
           while ((temp = br.readLine()) != null)
           {
               ret += temp;
           }
           if(!(ret.startsWith("{") && ret.endsWith("}"))) ret = ret.substring(ret.indexOf('{'),ret.lastIndexOf('}')+1);

           JSONObject jsonObject = new JSONObject(ret);

           return jsonObject;

       } catch (JSONException e) {
               e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
           return null;
       } catch (IOException e) {
           e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
           return null;
       }

   }
   
   /**
	 * 执行Get方法
	 * @return
	 */
	public static String executeHttpGet(String path) {  
		String result = null;
		URL url = null;
		HttpURLConnection connection = null;  
		InputStreamReader in = null;
		try {
			System.setProperty("http.keepAlive", "false"); 
			url = new URL(path);
			connection = (HttpURLConnection) url.openConnection();
			in = new InputStreamReader(connection.getInputStream()); 
			BufferedReader bufferedReader = new BufferedReader(in);
			StringBuffer strBuffer = new StringBuffer();
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				strBuffer.append(line);
			}
			result = strBuffer.toString();
			return result ;
		} catch (Exception e) {
			return null ;
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					return null ;
				}
			}

		}
	}

}
